import {Form, Input, Button, Select, message} from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import {addInterfaceInfoUsingPost} from '@/services/zhudiApi-backend/interfaceController';

// 构建表单项
const InterfaceForm = () => {
  const [form] = Form.useForm();

  const onFinish = (values) => {
    const parameters = values.parameters.map(param => {
      return {
        type: param.type,
        name: param.name,
        value: param.type === 'String' ? param.defaultValue : parseInt(param.defaultValue, 10),
      };
    });
    const requestData = {
      ...values,
      parameter: JSON.stringify(parameters),
    };
    console.log(requestData);
    addInterfaceInfoUsingPost(requestData).then(response => {
      // do something with response... like message.success() or form.resetFields()
    });
  };
  // @ts-ignore
  return (
    <Form form={form} name='dynamic_form_item' onFinish={onFinish} autoComplete='off'>
      <Form.Item name='description' label='描述'>
        <Input />
      </Form.Item>
      <Form.Item name='groupName' label='组名'>
        <Select>
          <Select.Option value='USER'>USER</Select.Option>
          <Select.Option value='ADMIN'>ADMIN</Select.Option>
        </Select>
      </Form.Item>
      <Form.Item
        name='name'
        label='接口名'
        rules={[
          { required: true, message: '请输入接口名' },
          { pattern: /^[a-zA-Z_$][a-zA-Z_$0-9]*$/, message: '只能输入以字母、美元符和下划线开头，后接字母、美元符、下划线或数字的标识符' }
        ]}
      >
        <Input />
      </Form.Item>
      <Form.List name='parameters'>
        {(fields, { add, remove }) => (
          <>
            {fields.map((field) => (
              <div key={field.key} style={{ display: 'flex', marginBottom: 8 }}>
                <Form.Item
                  {...field}
                  name={[field.name, 'name']}
                  fieldKey={[field.fieldKey, 'name']}
                  rules={[
                    { required: true, message: '请输入参数名称' },
                    { pattern: /^[a-zA-Z_$][a-zA-Z_$0-9]*$/, message: '只能输入以字母、美元符和下划线开头，后接字母、美元符、下划线或数字的标识符' }
                  ]}
                >
                  <Input placeholder='参数名' />
                </Form.Item>
                <Form.Item
                  {...field}
                  name={[field.name, 'type']}
                  fieldKey={[field.fieldKey, 'type']}
                  rules={[{ required: true, message: '请选择类型' }]}
                >
                  <Select placeholder='选择类型'>
                    <Select.Option value='String'>String</Select.Option>
                    <Select.Option value='Integer'>Integer</Select.Option>
                    <Select.Option value='Long'>Long</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  {...field}
                  name={[field.name, 'defaultValue']}
                  fieldKey={[field.fieldKey, 'defaultValue']}
                  rules={[
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value) {
                          return Promise.resolve();
                        }
                        const type = getFieldValue(['parameters', field.name, 'type']);
                        if ((type === 'String' && typeof value === 'string')
                          || ((type === 'Integer' || type === 'Long') && !isNaN(Number(value)))) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('默认值类型与参数类型不匹配'));
                      },
                    }),
                  ]}
                >
                  <Input placeholder='默认值' />
                </Form.Item>
                <MinusCircleOutlined style={{ margin: '0 8px' }} onClick={() => remove(field.name)} />
              </div>
            ))}
            <Form.Item>
              <Button type='dashed' onClick={() => add()} block icon={<PlusOutlined />}>
                添加参数
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item name='requestHeader' label='请求头'>
        <Input />
      </Form.Item>
      <Form.Item name='responseHeader' label='响应头'>
        <Input />
      </Form.Item>
      <Form.Item name='status' label='状态'>
        <Select>
          <Select.Option value={0}>禁用</Select.Option>
          <Select.Option value={1}>启用</Select.Option>
        </Select>
      </Form.Item>
      <Form.Item
        name='url'
        label='URL'
        rules={[{ required: true, message: 'URL不能为空' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item>
        <Button type='primary' htmlType='submit'>
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default InterfaceForm;
